package com.hotau.account;

import java.io.Serializable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TableLayout;

import com.hotau.HotauActivity;
import com.hotau.HotauConstants;
import com.hotau.R;
import com.hotau.ValueListener;
import com.hotau.account.mode.payment.AdvanceEntity;
import com.hotau.account.mode.payment.DetailAdapter;
import com.hotau.member.service.MemberService;
import com.hotau.util.DialogUtil;
import com.hotau.util.HttpRequestAsynTask;
import com.hotau.util.HttpUtil;

/**
 * 预付卡管理
 * @author liujia (liujia9234@126.com)
 * @data @2011-12-11
 * @version 1.0
 * <ul>
 * 		<li>1.0 创建</li>
 * </ul>
 */
public class PaymentAdvanceManageFragment extends Fragment implements
		OnClickListener,ValueListener, Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private TableLayout payment_layout_applyopen = null;
	private ListView payment_lv = null;
	private boolean isBind = false;
	private JSONArray jsonData = null;
	public DetailAdapter adapter = null;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initAllWidget();
		initAllEvent();
		if(isBind){
			getData();
		}
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		isBind = getArguments().getBoolean("isBind");
		jsonData = (JSONArray)getArguments().get("jsonData");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if(isBind){
			return inflater.inflate(R.layout.account_payment_advance_list, container,false);
		}else{
			return inflater.inflate(R.layout.account_payment_advance, container,false);
		}
	}
	
	

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(isBind){
			getData();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		HotauActivity csmbpActivity = (HotauActivity) getActivity();
		switch (v.getId()) {
		case R.id.account_payment_layout_applyopen:
			Bundle b = new Bundle();
			b.putSerializable("parentFragment", PaymentAdvanceManageFragment.this);
			BindPaymentAdvanceFragment f = new BindPaymentAdvanceFragment();
			csmbpActivity.pushFragment("绑定预付卡", f);
			break;
		default:
			break;
		}
	}
	


	/**
	 * 初始化所有控件
	 */
	public void initAllWidget() {
		if(isBind){
			payment_lv = (ListView) getActivity().findViewById(R.id.account_payment_lv);
			adapter = new DetailAdapter(getActivity(), hander, PaymentAdvanceManageFragment.this);
			payment_lv.setAdapter(adapter);
		}
		payment_layout_applyopen = (TableLayout) getActivity().findViewById(R.id.account_payment_layout_applyopen);
	}
	
	/**
	 * 初始化所有事件
	 */
	public void initAllEvent() {
		payment_layout_applyopen.setOnClickListener(this);
	}
	
	public void getData(){
		adapter.clearData();
		if(jsonData != null){
			for(int i =0 ;i<jsonData.length();i++){
				try {
					JSONObject json = jsonData.getJSONObject(i);
					AdvanceEntity entity = new AdvanceEntity();
					entity.setCardNo(json.getString("cardNo"));
					entity.setCardInfo(json.getString("cardInfo"));
					entity.setStatus(json.getString("status"));
					adapter.addItem(entity);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		adapter.notifyDataSetChanged();
	}
	
	public static final int ON_LOAD = 1; 
	public Handler hander = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			String payment_bind_url = HotauConstants.ACCOUNT_PAYMENT_BIND_URL;
			String temp_token = MemberService.getToken(getActivity());
			switch (msg.what) {
			case ON_LOAD:
				HttpRequestAsynTask payment_isbind_task = new HttpRequestAsynTask(getActivity()){
					HotauActivity csmbpActivity = (HotauActivity) getActivity();
					@Override
					protected void doPostExecute(String result) {
						try {
							JSONObject bindCardJson = new JSONObject(result);
							FragmentManager fragmentManager =getFragmentManager();
							FragmentTransaction transaction = fragmentManager.beginTransaction(); //通过begintransaction方法获取一个事物处理实例。
							if(bindCardJson != null && bindCardJson.getInt("result") == 1){
								//成功
								JSONArray cards = bindCardJson.getJSONArray("cardInfoList");
//								
//								transaction.remove(PaymentAdvanceManageFragment.this);
//								transaction.replace(PaymentAdvanceManageFragment.this.getId(), new PaymentAdvanceManageFragment(false,cards));
//								transaction.addToBackStack(null); 
//								transaction.commit();
//								csmbpActivity.pushFragment("预付卡管理 ", new PaymentAdvanceManageFragment(false,cards));
								PaymentAdvanceManageFragment.this.isBind = true;
								PaymentAdvanceManageFragment.this.jsonData = cards;
							}else if(bindCardJson != null && bindCardJson.getInt("result") == 2){
								//没有绑定相关卡
								PaymentAdvanceManageFragment.this.isBind = false;
								PaymentAdvanceManageFragment.this.jsonData = null;
//								csmbpActivity.pushFragment("预付卡管理 ", new PaymentAdvanceManageFragment(false,null));
							}else{
								//失败
								DialogUtil.showDialog(getActivity(), "", bindCardJson.getString("errorMsg"));
							}
//							onDestroy();
							getData();
//							onResume();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							DialogUtil.showDialog(getActivity(), "", "获取绑定预付卡返回数据出错 ");
						}
					}
				};
				StringBuilder data = new StringBuilder();
				data.append("Form:token="+temp_token);
				data.append(";terminalCode=" + HotauConstants.getTerminalCode(getActivity()));
				data.append(";sing="+"");
				
				payment_isbind_task.execute(payment_bind_url,data.toString(),HttpUtil.UTF8_ENCODING);
				
				break;
			default:
				break;
			}
		}
		
	};


	@Override
	public void passValue(int valueCode, String value) {
		// TODO Auto-generated method stub
		if(isBind){
			HttpRequestAsynTask payment_isbind_task = new HttpRequestAsynTask(getActivity()){
				HotauActivity csmbpActivity = (HotauActivity) getActivity();
				@Override
				protected void doPostExecute(String result) {
					try {
						JSONObject bindCardJson = new JSONObject(result);
						if(bindCardJson != null && bindCardJson.getInt("result") == 1){
							//成功
							JSONArray cards = bindCardJson.getJSONArray("cardInfoList");
							PaymentAdvanceManageFragment.this.jsonData = cards;
							getData();
//							csmbpActivity.pushFragment("预付卡管理 ", new PaymentAdvanceManageFragment(true,cards));
						}else{
							//失败
							DialogUtil.showDialog(getActivity(), "", bindCardJson.getString("errorMsg"));
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						DialogUtil.showDialog(getActivity(), "", "获取绑定预付卡返回数据出错 ");
					}
				}
			};
			StringBuilder data = new StringBuilder();
			data.append("Form:token="+MemberService.getToken(getActivity()));
			data.append(";terminalCode=" + HotauConstants.getTerminalCode(getActivity()));
			data.append(";sing="+"");
			payment_isbind_task.execute(HotauConstants.ACCOUNT_PAYMENT_BIND_URL,data.toString(),HttpUtil.UTF8_ENCODING);
			
		}
	}

}
